package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.article.ArticleConstants;
import com.heima.model.common.constants.message.NewsUpOrDownConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.ArticleHomeDTO;
import com.heima.model.wenmedia.pojos.WmNews;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {


    @Autowired
    ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private AdminFeign adminFeign;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private AuthorMapper authorMapper;
    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private GeneratePageService generatePageService;

    @Value("${file.oss.web-site}")
    private String webSite;

    @Override
    @GlobalTransactional(rollbackFor = Exception.class, timeoutMills = 100000)
    public void publishArticle(Integer newsId) {
        // 1. 查询并校验自媒体文章
        WmNews wmNews = getWmNews(newsId);
        // 2. 基于自媒体文章 封装ApArticle
        ApArticle article = getApArticle(wmNews);
        // 3. 保存或修改 article
        saveOrUpdateArticle(article);
        // 4. 保存article_config 和 article_content信息
        saveConfigAndContent(wmNews, article);
        //5.生成文章静态页
        generatePageService.generatePage(wmNews.getContent(),article);
        // 6. 更新wmNews状态 为 9  设置关联的articleId
        updateWmNews(wmNews, article);
        // 6. TODO 通知es索引库增加文章
        rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE,article.getId());
        log.info("文章发布成功，并发送索引库更新通知   文章id: {}",article.getId());
    }

    private void saveOrUpdateArticle(ApArticle article) {
        // 1. 判断  文章id是否存在
        if (article.getId() == null) {
            // 2. 如果不存在  保存文章信息
            // 阅读
            article.setViews(0);
            // 点赞
            article.setLikes(0);
            // 评论
            article.setComment(0);
            // 收藏
            article.setCollection(0);
            save(article);
        } else {
            // 3. 如果存在 修改文章信息  并删除之前关联的配置  内容
            ApArticle byId = getById(article.getId());
            if (byId == null) {
                log.error("发布文章失败  之前关联的文章不存在~ 文章id: {}", article.getId());
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            updateById(article);
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery()
                    .eq(ApArticleContent::getArticleId, article.getId())
            );

            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery()
                    .eq(ApArticleConfig::getArticleId, article.getId())
            );
        }
    }

    /*// 最大时间
    Date maxBehotTime;
    // 最小时间
    Date minBehotTime;
    // 分页size
    Integer size;
    // 频道ID
    String tag;*/

    @Value("${file.minio.readPath}")
    String readPath;

    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDTO dto) {
        Integer size = dto.getSize();
        //1 参数检查
        // 页大小
        if (size == 0 || size < 0) {
            size = 50;
        }
        // 频道
        if (StringUtils.isBlank(dto.getTag())) {
            //如果频道为空,则设置查询全部
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        // 时间
        //如果时间为空,则设置为当前时间
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        // 类型判断
        if (!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW) && !loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //通过调用mapper方法查询文章列表
        List<ApArticle> articles = apArticleMapper.loadArticleList(dto, loadtype);
        for (ApArticle apArticle : articles) {
            apArticle.setStaticUrl(readPath + apArticle.getStaticUrl());
        }
        //将返回值封装给结果
        ResponseResult result = ResponseResult.okResult(articles);
        //添加host
        result.setHost(webSite);

        return result;
    }

    @Autowired
    RedisTemplate redisTemplate;


    @Override
    public ResponseResult load2(Short loadtype, ArticleHomeDTO dto, boolean firstPage) {
        if(firstPage){
            String articleListJson=(String) redisTemplate.opsForValue().get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE+dto.getTag());
            if(StringUtils.isNotBlank(articleListJson)){
                List<ApArticle> apArticles = JSON.parseArray(articleListJson, ApArticle.class);
                for (ApArticle apArticle : apArticles) {
                    apArticle.setStaticUrl(readPath+apArticle.getStaticUrl());
                }
                ResponseResult result = ResponseResult.okResult(apArticles);
                result.setHost(webSite);
                return result;
            }
        }
        return load(loadtype,dto);
    }

    private void updateWmNews(WmNews wmNews, ApArticle article) {
        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        wmNews.setArticleId(article.getId());
        ResponseResult result = wemediaFeign.updateWmNews(wmNews);
        if (!result.checkCode()) {
            log.error("发布文章失败  原因: 远程修改自媒体文章状态失败 自媒体文章id:{}", wmNews.getId());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
    }

    private void saveConfigAndContent(WmNews wmNews, ApArticle article) {
        // 保存配置信息
        ApArticleConfig config = new ApArticleConfig();
        config.setArticleId(article.getId());
        // 是否可以评论
        config.setIsComment(true);
        // 是否可以转发
        config.setIsForward(true);
        //   // 是否下架
        config.setIsDown(false);
        // 是否被删除
        config.setIsDelete(false);
        apArticleConfigMapper.insert(config);
        // 保存内容信息
        ApArticleContent content = new ApArticleContent();
        content.setArticleId(article.getId());
        content.setContent(wmNews.getContent());
        apArticleContentMapper.insert(content);
    }

    private ApArticle getApArticle(WmNews wmNews) {
        // 1. 创建apArticle并拷贝属性  ( articleId  flag  layout)
        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(wmNews, article);
        article.setId(wmNews.getArticleId());
        // 文章类型  0 普通文章
        article.setFlag((byte) 0);
        // 封面 布局
        article.setLayout(wmNews.getType());
        // 2. 设置article频道信息
        ResponseResult<AdChannel> channelResult = adminFeign.findOne(wmNews.getChannelId());
        if (!channelResult.checkCode()) {
            log.error("发布文章失败  原因: 远程查询对应频道失败 {}", wmNews.getChannelId());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        AdChannel channel = channelResult.getData();
        if (channel == null) {
            log.error("发布文章失败  原因:未查询到对应的频道信息 {}", wmNews.getChannelId());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        article.setChannelId(wmNews.getChannelId());
        article.setChannelName(channel.getName());
        // 3. 设置article作者信息  根据wmUserId查询作者
        ApAuthor apAuthor = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery()
                .eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        if (apAuthor == null) {
            log.error("发布文章失败  原因:未查询到对应的作者信息   自媒体用户id:{}", wmNews.getUserId());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        article.setAuthorId(Long.valueOf(apAuthor.getId()));
        article.setAuthorName(apAuthor.getName());
        // 4. 返回ap_article
        return article;
    }

    private WmNews getWmNews(Integer newsId) {
        // 1. 远程查询自媒体文章
        ResponseResult<WmNews> result = wemediaFeign.findWmNewsById(newsId);
        if (!result.checkCode()) {
            log.error("远程调用 wemediaFeign失败  发布文章失败");
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        // 2. 校验不为空
        WmNews wmNews = result.getData();
        if (wmNews == null) {
            log.error("发布文章失败  对应自媒体文章不存在 {}", newsId);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "对应的文章数据不存在");
        }
        // 3. 校验状态必须时 4 或 8
        short status = wmNews.getStatus().shortValue();
        if (status != WmNews.Status.ADMIN_SUCCESS.getCode() && status != WmNews.Status.SUCCESS.getCode()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "当前文章状态不为4 或 8");
        }
        return wmNews;
    }
}